package vip.xiaonuo.common.util;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @author zjt
 * @description
 * @date 2025/4/2 18:14
 */
public class CommonSignatureUtils {

    /**
     * 生成MD5签名（不推荐）
     *
     * @param nonce     随机字符串
     * @param apiKey    客户端API Key
     * @param apiSecret 客户端API Secret
     * @param timestamp 时间戳
     * @return MD5签名（32位小写）
     */
    public static String generateMd5Signature(String nonce, String apiKey, String apiSecret, String timestamp) {
        // 拼接字符串：nonce + apiKey + apiSecret + timestamp
        String rawData = nonce + apiKey + apiSecret + timestamp;
        return CommonCryptogramUtil.doMd5(rawData);
    }

    /**
     * 验证签名是否匹配
     *
     * @param request HTTP请求
     * @return 是否验证通过
     */
    public static boolean verifyMd5Signature(HttpServletRequest request) {
        String apiKey = request.getHeader("apiKey");
        String apiSecret = request.getHeader("apiSecret");
        String timestamp = request.getHeader("timestamp");
        String nonce = request.getHeader("nonce");
        String clientSignature = request.getHeader("signature");

        // 服务端重新计算签名
        String serverSignature = generateMd5Signature(nonce, apiKey, apiSecret, timestamp);
        return serverSignature.equalsIgnoreCase(clientSignature);
    }
}
